<?php

class ArticleApi extends ApiBase
{
	private $mysql = null;

	public function __construct()
	{
		parent::__construct();
		$this->mysql = n_api('mysql')->cname('weixin');
		$this->redis = n_api('redis')->scrapy;
	}

	public function getHotArticleAll($num)
	{
		$query = "select article_id from article_day where daytime = (select max(daytime) from article_day) order by read_like desc limit $num";
		$rs = $this->mysql->select($query);
		foreach ($rs as $value) {
			$articleIds[] = $value['article_id'];
		}
		if (count($articleIds) == 0)
			return [];
		$query = 'select article_mongoid, title, digest as content168, url, cover as imgLink, article_ptime from article_details where id in (' . implode(',', $articleIds) . ')';
		return $this->mysql->select($query);
	}

	public function getHotArticleByCategoryId($cid, $date, $type, $skip, $limit)
	{
		// $key = "expire:article:getHotArticleByCategoryId:$cid:$date:$type:$skip:$limit";
		// $categoryArticle = $this->redis->get($key);

		// if (!$categoryArticle) {
			$rs = n_api('weixin')->getWxidsByCategoryId($cid);
			$wxids = [];
			foreach ($rs as $value) {
				$wxids[] = "'{$value['wxid']}'";
				$wxInfo[$value['wxid']] = $value['wxname'];
			}

			if (count($wxids) == 0)
				return [];

			if ($type == 'day')
				$query = "select article_id, read_num, like_num from article_day where daytime = $date and wxid in (" . implode(',', $wxids) . ") order by read_like desc limit $skip, $limit";
			else if ($type = 'week') {
				$stime = $date;
				$etime = $date + 7 * 24 * 3600;
				$query = "select article_id, read_num, like_num from article_day where daytime >=$stime and daytime < $etime and wxid in (" . implode(',', $wxids) . ") order by read_like desc limit $skip, $limit";
			}
			$query = "select wxid,article_id, read_num, like_num from article_day where daytime = $date and wxid in (" . implode(',', $wxids) . ") order by read_like desc limit $skip, $limit";
			$articleDay = $this->mysql->select($query);
			foreach ($articleDay as $value) {
				$articleIds[] = $value['article_id'];
			}

			if (count($articleIds) == 0)
				return [];
			
			$query = 'select id, article_mongoid, title, digest as content168, url, cover as imgLink, article_ptime from article_details where id in (' . implode(',', $articleIds) . ')';
			$rs = $this->mysql->select($query);

			foreach ($rs as $value) {
				$articleDetails[$value['id']] = $value;
			}

			$data = [];
			foreach ($articleDay as $value) {
				$value['wxname'] = $wxInfo[$value['wxid']];
				$detail = $articleDetails[$value['article_id']];
				unset($detail['id']);
				$data[] = array_merge($value, $detail);
			}
			$categoryArticle = json_encode($data);

			$this->redis->set($key, $categoryArticle);
		// } // end redis get

		return json_decode($categoryArticle, true);
	}

	public function getMaxArticleDay()
	{
		// $key = 'expire:article:getMaxArticleDay';
		// $maxday = $this->redis->get($key);
		// if (!$maxday) {
			$query = 'select max(daytime) as day from article_day';
			$rs = $this->mysql->fetchFirst($query);
			$maxday = $rs['day'];

		// 	$this->redis->setex($key, 3600, $maxday);
		// }
		return $maxday;
	}

	public function getMaxArticleWeek()
	{
		return strtotime('-2 sunday');   
	}

	public function getHotArticleWeek($wxid, $num=3)
	{
		$stime = strtotime('-2 sunday');
		$etime = strtotime('-1 sunday');
		$query = "select article_id, read_num, like_num from article_day where daytime >= $stime and daytime < $etime and wxid = '$wxid' order by read_like desc limit $num";
		$infos = $this->mysql->select($query);
		foreach ($infos as $value) {
			$articleIds[] = $value['article_id'];
		}
		if (count($infos) == 0)
			return [];
		$query = "select id, title, digest as content168, url,article_ptime from article_details where id in (" . implode(',', $articleIds) . ")";
		$detail = $this->mysql->select($query);
		foreach ($detail as $value) {
			$detailRs[$value['id']] = $value;
		}
		foreach ($infos as $value) {
			$id = $value['article_id'];
			$value['title'] = $detailRs[$id]['title'];
			$value['content168'] = $detailRs[$id]['content168'];
			$value['url'] = $detailRs[$id]['url'];
			$value['ptime'] = $detailRs[$id]['article_ptime'];
			unset($value['article_id']);
			$rs[] = $value;
		}
		return $rs;
	}

	public function getHotArticleDay($wxid, $num=3)
	{
		$query = "select article_id, read_num, like_num from article_day where wxid = '$wxid' order by daytime desc limit $num";
		$infos = $this->mysql->select($query);
		foreach ($infos as $value) {
			$articleIds[] = $value['article_id'];
		}
		if (count($articleIds) == 0)
			return [];
		$query = "select id, title, digest as content168, url,article_ptime from article_details where id in (" . implode(',', $articleIds) . ")";
		$detail = $this->mysql->select($query);
		foreach ($detail as $value) {
			$detailRs[$value['id']] = $value;
		}
		foreach ($infos as $value) {
			$id = $value['article_id'];
			unset($value['article_id']);
			$value['title'] = $detailRs[$id]['title'];
			$value['content168'] = $detailRs[$id]['content168'];
			$value['url'] = $detailRs[$id]['url'];
			$value['ptime'] = $detailRs[$id]['article_ptime'];
			$rs[] = $value;
		}
		return $rs;
	}

	public function getArticleCountByDay($day)
	{
		$query = "select count(*) as sum from article_details where ctime >= $day";
		$rs = $this->mysql->fetchFirst($query);
		return $rs['sum'];
	}

	public function getAllArticle()
	{
		$query = "select count(*) as sum from article_details";
		$rs = $this->mysql->fetchFirst($query);
		return $rs['sum'];
	}

	public function getArticleList($skip, $limit)
	{
		$query = "select id, title, digest as content168, url, article_ptime from article_details order by id desc limit $skip, $limit";
		$rs = $this->mysql->select($query);

		foreach ($rs as $value) {
			$articleIdArr[] = $value['id'];
		}
		$articles = $rs;

		$query = "select article_id, wxid from article_day where article_id in (" . implode(',', $articleIdArr) . ")";
		$rs = $this->mysql->select($query);
		foreach ($rs as $value) {
			$wxnameArr[$value['article_id']] = $value['wxid'];
		}

		$articleArr = [];
		foreach ($articles as $article) {
			$article['wxname'] = $wxnameArr[$article['id']];
			$articleArr[] = $article;
		}

		return $articleArr;
	}
	public function getNewArticle($cid,$limit=20){
		$query = "select id, title, digest as content168, url, article_ptime from article_details where  order by id desc limit $limit";
		return $this->mysql->selectIndex($query);
	}

	public function getRecentArticle($cate, $skip=0, $limit=20) {
		$mongo = new MongoClient("mongodb://newbee:9^4%NbAdwS@115.28.18.40:27017");
		$articleCollection = $mongo->selectDB('weixin')->selectCollection('article');
	
		$weixin = n_api('weixin');
		$categories = $weixin->getCategories();

		$cates = [];
		foreach ($categories as $value)
			$cates[$value['second_category']] = $value['id'];

		if (!array_key_exists($cate, $cates))
			return [];
		else {
			$cid = $cates[$cate];
			$wxids = $weixin->getWxidsByCategoryId($cid);

			$data = array('wx'=>array(),'article'=>array());
			$wxidArr = [];
			foreach ($wxids as $value){
				$wxidArr[] = $value['wxid'];
				$data['wx'][$value['wxid']] = $value;
			}
			$rs = $articleCollection->find(['wxid'=>['$in'=>$wxidArr]], ['wxid'=>1,'title'=>1, 'contentUrl'=>1, 'digest'=>1, 'ptime'=>1])->sort(['ptime'=>-1])->skip($skip)->limit($limit);
			foreach ($rs as $value) {
				$data['article'][] = $value;
			}
			return $data;
		}
	}
	
	public function getNewArticleByWxid($wxid,$num=5){
		$mongo = new MongoClient("mongodb://newbee:9^4%NbAdwS@115.28.18.40:27017");
		$articleCollection = $mongo->selectDB('weixin')->selectCollection('read');
		$read = $articleCollection->find(array('wxid'=>$wxid))->sort(array('_id'=>-1))->limit(5);
		foreach($read as $key=>$val){
			$aids[] = new MongoId($val['articleId']);
		}
		if (count($aids) == 0)
			return [];
		$read = iterator_to_array($read);
		$articleCollection = $mongo->selectDB('weixin')->selectCollection('article');
		$data = $articleCollection->find(array('_id'=>array('$in'=>$aids)),array('wxid'=>1,'title'=>1, 'contentUrl'=>1, 'digest'=>1, 'ptime'=>1))->sort(array('_id'=>-1))->limit(5);
		$rs = iterator_to_array($data);
		foreach($read as $key=>$val){

			$rs[$val['articleId']] = array_merge($val,$rs[$val['articleId']]);
		}
		return $rs;
	}
	
	public function subtxt($text){
		if(mb_strlen($text, 'utf8') > 50) 
		return mb_substr($text, 0, 50, 'utf8').'...';
		return $text;
	}
}